/**
 * 公用函数方法
 */
'use strict'
import Vue from 'vue'
import { Message } from 'element-ui';

let util = {}
/*
 *两个数组对象去重得到新的数组
 *@obj对象包含三个参数：
 *@old ->原始对象；
 *@new -> 新对象；
 *@unique ->数组对象中的属性（改属性值为唯一标识）
 *@temp -> 临时变量
 *@sort --> 新数据插入旧数据的顺序，order再尾部插入，不传再插入最开始
 *@return 返回新的数组
 */
util.repeatData = (obj) => {
    var oldData = obj.old;
    var newData = obj.new;
    var unique = obj.unique;
    var sort = obj.sort
    var temp = oldData;
    var same = false;  //重复标识
    for(var i = 0;i<newData.length;i++){ //循环选中的数据
        if(oldData.length == 0){
            temp.unshift(newData[i]); //如果老数据长度为0 ，把新数据直接加入
        }else{
            var flag=false;
            for(var j = 0;j<oldData.length;j++){ //如果老数据长度不为0  循环老数据 对比唯一标识
                if(newData[i][unique] == oldData[j][unique]){
                     flag = true; //true,则存在相同数据
                    break;
                }
            }
            if(!flag){
                if( sort == 'order'){
                    temp.push(newData[i]); // 后面存入不相同的新数据

                }else{
                    temp.unshift(newData[i]); // 在前面插入不相同的新数据
                }

            }else{
                same = true;
            }
        }
    }
    var msg="";
        if(same){
            msg = '已为您过滤掉相同选项!'
        }else{
            msg = '已加入选中的选项!'
        }
        Message({
            type: 'success',
            message: msg
        });
        return temp;

}
/*
 * 状态字段转换方法 （客户 、样品类型、检测点类型等数据字典数据）
 * @obj 对象 必须包含 cellValue，list字段
 * @list 数组对象
 */
util.codeChangeName = (obj) =>{
    var cellValue =obj.cellValue;
    var list =obj.list;
    // if(cellValue == undefined || cellValue==''){
    //  return "";
    // }
    var res = null;
    for(var i in list){
        if(cellValue === list[i].code){
            res = list[i].name;
        }
    }
    return res ? res : cellValue;
}
// 转换状态数据
util.changeStatus = (obj) =>{
    //var list =obj.list;
    // for(var i in list){
    //   list[i].code = list[i].value;
    //    list[i].name = list[i].label;
    // }
  // util.codeChangeName(obj);

   var cellValue =obj.cellValue;
    var list =obj.list;
    var res = null;
    for(var i in list){
        if(cellValue == list[i].value){
            res = list[i].label;
        }
    }
    return res ? res : cellValue;
}
// 去掉时间的时分秒
util.formatterDate = (obj) =>{
  if(obj.cellValue){
    var cellValue =obj.cellValue;
    var newDate=/\d{4}-\d{1,2}-\d{1,2}/g.exec(cellValue);
    return newDate;
  }else{
    return '---'
  }

}
/*
 * 删除数组中指定一些对象
 * @param obj 对象 必须包含 allArr,delArr,unique 三个字段
 * @return list 数组对象
 */
util.deleteArrSomeObj = (obj) =>{
    var allArr = obj.allArr;var delArr = obj.delArr;var unique = obj.unique;
    var map ={};var temp=[];
    for(var i in allArr){
        map[i]= allArr[i];
        for(var j in delArr){
            if(delArr[j][unique] ==allArr[i][unique]){
                delete map[i];
                break;
            }
        }
    }
    for(var i in map){
        temp.push(map[i]);
	}
    return temp;
}

util.date = (s) => {
	let day = new Date()
	let res
    day.setTime(day.getTime())
    let year = day.getFullYear()
    let month= day.getMonth()
    let d = day.getDate()
    if (s === 'month') {
    	res = year +"-" + (month+1 <10 ? "0" + (month+1):(month+1))
    }else if (s === 'lastMonth'){
    	res = year +"-" + (month <10 ? "0"+month:month)
    }else if (s === 'halfYear'){
    	res =  year + "-" + (month- 5 <10 ? "0" + (month-5):(month-5))
    }else if (typeof(s) === 'number'){
    	day.setTime(day.getTime() + s)
    	 let year = day.getFullYear()
   		 let month= day.getMonth()
    	 let d = day.getDate()
    	res =  year + "-" + (month+1) + "-" + d
    }else {
    	res = year + "-" + (month+1 <10? "0" + (month+1) : month+1 ) + "-" + (d<10? "0"+d:d)
    }
    return res
}

/*
 * 判断对象中的属性是否存在，不存在则返回false,否则返回true
 * @param obj 对象 obj: data,valueArr
 * @return
 */
util.operateArr = (obj) => {
    for(var i in obj.valueArr){ //遍历页面本身的按钮
       var temp = false;
       for(var j in obj.data){ //遍历接口的按钮
            if(obj.valueArr[i] == j){
                temp = true;
                obj.data[j].display = true;
            }
        }
        if(!temp){
           var shuxing = obj.valueArr[i];
           obj.data[shuxing] = {};
           obj.data[shuxing].display = false;
        }
    }
    return obj.data;
}
/*
 * 输入一个对象，判断对象中操作栏是否应该隐藏，若该返回 false,不该返回true;
 * @param obj 对象 obj
 * @return
 */
util.operate = (obj) => {
    var flag = 1
    for(var i in obj){ //遍历页面接口的按钮
       if(!obj[i].display){
          flag = flag *1
       } else{
          flag = flag *0;
       }
    }
    if(flag == 1){
        return false; //所有的按钮都应该隐藏
    }else{
        return true; //部分按钮都应该显示
    }
}
/* 审核按钮
 * 输入一个对象，判断对象中操作栏是否应该隐藏，若该返回 false,不该返回true;
 * @param obj 对象 obj
 * data  是页面数据
 * @return
 */
util.showOpreta = (obj) =>{
    for(var i in obj.data){
        if(obj.data[i].isApprove !=undefined && obj.data[i].isApprove){
            return true
        }
    }
    return false;
}
util.getModuleId = (obj) =>{
    var module = obj.module;
    var allModule = JSON.parse(sessionStorage.getItem('premodelDataJson'));
    for(var i in allModule){
        if(allModule[i].pageAddress == module){
            return allModule[i].id;
        }
    }
}
util.generateMixed = (obj) =>{
    var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
    var res = "";
    for (var i = 0; i < obj.number; i++) {
        var id = Math.ceil(Math.random() * 35);
        res += chars[id];
    }
    return res;
}
util.tableToExcel = function (el, name) {
  let table = el.childNodes[1].childNodes[0]
  let body = el.childNodes[2].childNodes[0]

  return  table.innerHTML + body.childNodes[1].innerHTML
}
//后台返回二进制，进行blob，前提‘请求类型必须为blob’
util.resultFileBlob = function (res,name,ext='.xls') {
  console.log(res)
  let blob = new Blob([res.data])
  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob, `${name}${ext}`);
  } else {
    let blobUrl = window.URL.createObjectURL(blob);
    var a = document.createElement('a');
    a.download = `${name}${ext}`;
    a.href = blobUrl;
    a.click();
  }
}
util.tableFormatter = function(...arg) {
  let cellValue = arg[0][arg[1]['property']]
  if (cellValue == undefined || cellValue == null || cellValue == '') {
    return '---'
  } else {
    return cellValue
  }
}
util.changeRange = function(val,row){
    let range = ""
    if(row.hasOwnProperty('value') && row.value != ''){
      range = row.value
    }
    if(row.hasOwnProperty('low') && row.low != '' && (!row.hasOwnProperty('high') || row.high == '')){ // 只有下限
      if(row.equalLow){ //  >下限
        range = ">" + row.low
      }else{ //  >=下限
        range = "≥" + row.low
      }
    }
    if(row.hasOwnProperty('high') && row.high != '' && (!row.hasOwnProperty('low') || row.low == '')){ // 只有上限
      if(row.equalHigh){ //<上限
        range = "<" + row.high
      }else{ //<=上限
        range = "≤" + row.high
      }
    }
    if(row.hasOwnProperty('high') && row.high != '' && row.hasOwnProperty('low') && row.low != ''){ //上下限都有值
      if(row.equalLow && row.equalHigh){
        range =row.low + "(>)" + "-" + "(<)" + row.high
      }
      if(!row.equalLow && row.equalHigh){
        range =row.low  + "-" + "(<)" + row.high
      }
      if(row.equalLow && !row.equalHigh){
         range =row.low + "(>)" + "-" + row.high
      }
      if(!row.equalLow && !row.equalHigh){
        range =row.low  + "-" + row.high
      }
    }
    return range
  }
util.getStationName = function(){
	var data = JSON.parse(sessionStorage.getItem('stationList'))
	var stationName = "厂站"
	if(data.length > 0){
	  if(data[0].desc){
	    stationName = data[0].desc
	  }
	}
	return stationName
}
util.getStationList = function(){
  var stationList =JSON.parse(sessionStorage.getItem('stationList'));
	var stations =JSON.parse(sessionStorage.getItem('laboratoryAccountInfo')).idcard;
	var arr = []
	if(stations){
	  arr = stations.split(',')
	}
	var stationList1 = [];
	arr.forEach((item) =>{
	  stationList.forEach((item1) =>{
	     if(item == item1.id){
	       stationList1.push(item1)
	     }
	  })

	})
	return stationList1
}
export default util
